<script setup>
import {pushScopeId, reactive, ref} from 'vue';
import router from '@/router/index.js';
import userApi from '@/api/user_api.js';
import loginApi from '@/api/login_api.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Stamp, SwitchButton, Shop, Grid, User, Collection, Document, ShoppingCart,
  Setting, Folder, Star, List, PieChart, UserFilled, ShoppingBag
} from '@element-plus/icons-vue';


const activeIndex = ref('1')

// 存储当前登录用户的信息
const loginAdmin = ref({
  username: "未登录",
});
// 修改信息表单
const editForm = ref({
  username: '',
  email: '',
  phone: '',
  avatar: ''
})
// 修改信息表单规则
const editFormRules = {
  username: [
    {message: '请输入用户名', trigger: 'blur' }
  ],
  email: [
    {message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  phone: [
    {message: '请输入手机号', trigger: 'blur' },
    { type: 'string', min: 11, max: 11, message: '请输入正确的手机号', trigger: ['blur', 'change'] }
  ]
}
// 重置密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmNewPassword: ''
})
// 重置密码表单引用
const passwordFormRef = ref(null)
// 重置密码表单规则
const passwordFormRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmNewPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateNewPassword, trigger: 'blur' }
  ]
}
// 验证新密码确认是否一致
function validateNewPassword(rule, value, callback) {
  if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
}

// 获取当前登录用户信息
getLogin();

// 修改信息对话框显示状态
const editDialogVisible = ref(false)

// 重置密码对话框显示状态
const passwordDialogVisible = ref(false)

// 用户下拉菜单的点击
function handleSelect(key, keyPath){
  if (key == 'logout'){
    // 用户退出
    logout();
  }else if (key == '1-1') {
    // 修改信息
    openEditDialog();
  } else if (key == '1-2') {
    // 重置密码
    openPasswordDialog();
  }
}
// 打开修改信息对话框
function openEditDialog() {
  editDialogVisible.value = true;
}
// 打开重置密码对话框
function openPasswordDialog() {
  passwordDialogVisible.value = true;
  // 重置表单
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmNewPassword: ''
  }
}
// 关闭修改信息对话框
function closeEditDialog() {
  editDialogVisible.value = false;
}

// 关闭重置密码对话框
function closePasswordDialog() {
  passwordDialogVisible.value = false;
}

// 提交修改信息
async function submitEditForm() {
  try {
    await userApi.updateUser(editForm.value);

    // 更新显示的用户名
    loginAdmin.value.username = editForm.value.username;
    // 更新邮箱
    loginAdmin.value.email = editForm.value.email;
    //更新手机号
    loginAdmin.value.phone = editForm.value.phone;
    // 更新头像
    loginAdmin.value.avatar = editForm.value.avatar;

    closeEditDialog();
    ElMessage.success('信息修改成功');

    // 发送全局事件通知 profile 页面刷新数据
    window.dispatchEvent(new CustomEvent('user-info-updated'));
  } catch (err) {
    ElMessage.error('信息修改失败');
  }
}

// 获取当前登录用户信息
async function getLogin() {
  let token = localStorage.getItem('token');
  if (!token) {
    await router.push('/login'); // 跳转到登录页
  }

  try {
    const res = await loginApi.logininfo();
    loginAdmin.value = res;

    // 同时更新编辑表单的数据
    editForm.value.id = res.id;
    editForm.value.username = res.username;
    editForm.value.email = res.email || '';
    editForm.value.phone = res.phone || '';
    editForm.value.avatar = res.avatar || '';
  } catch (error) {
    ElMessage.error('获取用户信息失败');
  }
}

// 提交密码重置
// 提交密码重置
async function submitPasswordForm() {
  try {
    // 先进行表单验证
    const valid = await passwordFormRef.value.validate();
    if (!valid) {
      return; // 验证失败，不继续执行
    }

    const passwordData = {
      username: loginAdmin.value.username,
      oldPassword: passwordForm.value.oldPassword,
      newPassword: passwordForm.value.newPassword
    };

    const response = await userApi.resetPassword(passwordData);

    // 无论 response 是什么值，只要没有异常就说明成功
    ElMessage.success('密码修改成功');
    closePasswordDialog();
    await router.push('/login');
  } catch (error) {
    // 只有在出现异常时才认为失败
    ElMessage.error('密码修改失败: ' + (error.message || '未知错误'));
  }
}

// 左侧菜单动作
function handleMenu(key){
  if (key){
    router.push(key);
  }
}

// 退出
function logout(){
  // 清除Token
  localStorage.removeItem('token')
  // 跳转到登录
  router.push('/login')
}

// 处理头像上传成功
const handleUploadSuccess = (response, file) => {
  console.log("-----------------");
  console.log(response);
  console.log(file);
  editForm.value.avatar = response.data;
}
</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <el-menu
            :default-active="activeIndex"
            class="el-menu-demo"
            mode="horizontal"
            :ellipsis="false"
            background-color="#171a21"
            text-color="#b8b6b4"
            active-text-color="#ffffff"
            @select="handleSelect"
        >
          <el-menu-item index="0" class="logo-item">
            <img src="../../assets/logo.png" alt="抢鲜购" class="logo" />
            <span class="logo-text">抢鲜购</span>
          </el-menu-item>
          <div class="flex-grow" />
          <el-sub-menu index="1" class="user-menu">
            <template #title>
              <el-icon><Stamp /></el-icon>
              <span class="username">{{ loginAdmin ? loginAdmin.username : '未登录' }}</span>
            </template>
            <el-menu-item index="1-1">
              <el-icon><User /></el-icon>
              修改信息
            </el-menu-item>
            <el-menu-item index="1-2">
              <el-icon><Setting /></el-icon>
              重置密码
            </el-menu-item>
            <el-menu-item index="logout">
              <el-icon><SwitchButton /></el-icon>
              退出
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-header>

      <el-container>
        <el-aside width="200px">
          <el-menu
              active-text-color="#1a9fff"
              background-color="#ffffff"
              class="el-menu-vertical-demo"
              default-active="/passenger/map-order"
              text-color="#ffffff"
              @select="handleMenu"
              :unique-opened="true"
          >
            <!-- 用户功能菜单 -->
            <el-sub-menu index="1">
              <template #title>
                <el-icon><Grid /></el-icon>
                <span>管理员界面</span>
              </template>
              <el-menu-item index="/admin/adminList">
                <el-icon><Management /></el-icon>
                <span>管理员列表</span>
              </el-menu-item>
              <el-menu-item index="/admin/userList">
                <el-icon><User /></el-icon>
                <span>用户列表</span>
              </el-menu-item>
              <el-menu-item index="/admin/deliveryAddr">
                <el-icon><ShoppingBag /></el-icon>
                <span>用户地址管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/goods">
                <el-icon><ShoppingCart /></el-icon>
                <span>商品管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/order">
                <el-icon><Document /></el-icon>
                <span>订单管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/orderAddr">
                <el-icon><Document /></el-icon>
                <span>订单地址管理</span>
              </el-menu-item>
<!--              <el-menu-item index="/admin/paymentList">
                <el-icon><ShoppingCart /></el-icon>
                <span>订单支付管理</span>
              </el-menu-item>-->
              <el-menu-item index="/admin/seckill/seckillGoods">
                <el-icon><ShoppingBag /></el-icon>
                <span>秒杀商品管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/seckill/seckillActivity">
                <el-icon><ShoppingBag /></el-icon>
                <span>秒杀活动管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/seckill/seckillOrder">
                <el-icon><ShoppingBag /></el-icon>
                <span>秒杀订单管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/seckill/seckillResult">
                <el-icon><ShoppingBag /></el-icon>
                <span>秒杀结果管理</span>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>


        <!-- 主内容区域 -->
        <el-main>
          <!-- 根据路由显示不同的内容 -->
          <template v-if="$route.path === '/admin/adminIndex'">
            <div class="welcome-image-container">
              <img src="@/assets/main.png" alt="欢迎来到抢鲜购管理员系统" class="welcome-image">
            </div>
          </template>

          <!-- 其他页面的内容 -->
          <template v-else>
            <router-view></router-view>
          </template>
        </el-main>
      </el-container>
    </el-container>
  </div>

  <!-- 修改信息对话框 -->
  <el-dialog v-model="editDialogVisible" title="修改信息" width="500px" class="custom-dialog">
    <el-form :model="editForm" :rules="editFormRules" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="editForm.username" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="editForm.phone" />
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload
            class="avatar-uploader"
            action="/api/user/upload/file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
        >
          <img v-if="editForm.avatar" :src="editForm.avatar" style="width: 100px; height: 100px; object-fit: cover;" />
          <img v-else src="../../assets/upload.png" style="width: 100px; height: 100px;" />
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeEditDialog" class="cancel-button">取消</el-button>
        <el-button type="primary" @click="submitEditForm" class="confirm-button">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 重置密码对话框 -->
  <el-dialog v-model="passwordDialogVisible" title="重置密码" width="500px" class="custom-dialog">
    <el-form :model="passwordForm" :rules="passwordFormRules" label-width="100px" ref="passwordFormRef">
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="passwordForm.oldPassword" type="password" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordForm.newPassword" type="password" show-password />
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmNewPassword">
        <el-input v-model="passwordForm.confirmNewPassword" type="password" show-password />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closePasswordDialog" class="cancel-button">取消</el-button>
        <el-button type="primary" @click="submitPasswordForm" class="confirm-button">确定</el-button>
      </span>
    </template>
  </el-dialog>


</template>

<style scoped>
.common-layout,
.el-container {
  height: 100vh;
}

.welcome-image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 850px; /* 设置容器高度 */
  margin-bottom: 20px;
}

.welcome-image {
  width: 1400px; /* 设置图片宽度 */
  height: 800px; /* 设置图片高度 */
  object-fit: contain; /* 保持图片比例，防止变形 */
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 顶部导航栏 - 淘宝主色调优化 */
.el-header {
  padding: 0;
  background-color: #ff6b00; /* 调整为更柔和的橙色 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1000;
}

.el-menu.el-menu--horizontal {
  border: none;
  background-color: #ff6b00;
}

.el-menu-item.logo-item {
  background-color: #ff6b00 !important;
  padding-left: 20px !important;
}

.logo {
  height: 32px;
  margin-right: 12px;
  vertical-align: middle;
}

.logo-text {
  color: white;
  font-size: 19px;
  font-weight: 600;
  vertical-align: middle;
}

.flex-grow {
  flex-grow: 1;
}

.user-menu :deep(.el-sub-menu__title) {
  background-color: #ff6b00 !important;
  color: white !important;
  height: 60px;
  padding-right: 20px !important;
  transition: background-color 0.3s;
}

.user-menu :deep(.el-sub-menu__title:hover) {
  background-color: #e55a00 !important; /* 深一点的橙色 */
}

.username {
  margin-left: 6px;
}

/* 侧边栏样式 - 淘宝辅助色系 */
.el-aside {
  background-color: #fff9f2; /* 淘宝浅橙色背景 */
  box-shadow: 2px 0 10px rgba(255, 68, 0, 0.1);
  transition: width 0.3s ease;
  position: relative;
  z-index: 999;
  height: calc(100vh - 60px);
}

.el-menu-vertical-demo {
  border: none !important;
  height: 100%;
  background-color: white;
}

.el-menu-vertical-demo :deep(.el-sub-menu__title) {
  height: 50px;
  font-size: 15px;
  color: #333;
  background-color: transparent;
  border-bottom: 1px solid #fff9f2;
  padding-left: 25px !important;
  transition: all 0.2s;
}

.el-menu-vertical-demo :deep(.el-sub-menu__title:hover) {
  background-color: #fff2e8 !important; /* 悬停浅橙色 */
  color: #ff6b00 !important;
}

.el-menu-vertical-demo :deep(.el-menu-item) {
  height: 45px;
  font-size: 14px;
  color: #666;
  border-bottom: 1px solid #fffaf5;
  padding-left: 45px !important;
  transition: all 0.2s;
}

.el-menu-vertical-demo :deep(.el-menu-item:hover) {
  background-color: #fff2e8 !important;
  color: #ff6b00 !important;
}

.el-menu-vertical-demo :deep(.el-menu-item.is-active) {
  color: #ff6b00 !important;
  background-color: #fff2e8 !important;
  font-weight: 500;
  border-left: 3px solid #ff6b00;
}

/* 主内容区域 - 淘宝风格背景 */
.el-main {
  background-color: #fafafa; /* 淘宝浅灰色背景 */
  padding: 20px;
  overflow-y: auto;
}

/* 对话框样式 - 淘宝风格弹窗 */
.custom-dialog :deep(.el-dialog__header) {
  background-color: #ff6b00;
  color: white;
  padding: 15px 20px;
}

.custom-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 500;
}

.custom-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  transition: all 0.2s;
}

.custom-dialog :deep(.el-dialog__headerbtn .el-dialog__close:hover) {
  background-color: rgba(255, 255, 255, 0.2);
}

.custom-dialog :deep(.el-dialog__body) {
  padding: 20px;
  background-color: white;
}

.custom-dialog :deep(.el-dialog__footer) {
  padding: 15px 20px;
  background-color: #fafafa;
  border-top: 1px solid #eee;
}

/* 按钮样式 - 淘宝风格按钮 */
.confirm-button {
  background-color: #ff6b00 !important;
  border-color: #ff6b00 !important;
  color: white !important;
  transition: all 0.2s !important;
}

.confirm-button:hover {
  background-color: #e55a00 !important;
  border-color: #e55a00 !important;
}

.cancel-button {
  border-color: #ff6b00 !important;
  color: #ff6b00 !important;
  background-color: transparent !important;
  transition: all 0.2s !important;
}

.cancel-button:hover {
  background-color: #fff9f2 !important;
}

/* 表单元素样式优化 */
:deep(.el-input__wrapper) {
  border-radius: 4px;
  transition: all 0.2s;
}

:deep(.el-input__wrapper:focus-within) {
  box-shadow: 0 0 0 2px rgba(255, 107, 0, 0.2) !important;
  border-color: #ff6b00 !important;
}

:deep(.el-upload) {
  transition: all 0.2s;
}

:deep(.el-upload:hover) {
  filter: brightness(1.05);
}

/* 动画效果增强 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease-in-out;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式设计优化 */
@media (max-width: 768px) {
  .logo-text {
    display: none;
  }

  .el-menu-item.logo-item {
    padding-right: 20px !important;
  }

  .el-aside {
    width: 64px !important;
  }

  .el-menu-vertical-demo :deep(.el-sub-menu__title span),
  .el-menu-vertical-demo :deep(.el-menu-item span) {
    display: none;
  }

  .el-menu-vertical-demo :deep(.el-menu-item) {
    padding-left: 20px !important;
  }
}
</style>
